'use strict'

const Sequelize = require('sequelize');//操作数据库
const fs = require('fs');//文件操作
const ApiClient = require('../server/taobao.js').ApiClient;//淘宝API
const Taobao = require('../server/taobao.js').Taobao;
const WebSocket = require('ws');

//前台API，可获取授权
/*var config = {
 app_key:"23164248",
 app_secret:"ea9dbcf8c9dddf13b57fcdd8f1f63b32",
 redirect_uri:"http://vrbuy.ews.m.jaeapp.com/oauth2"
 }
 var frontClient = new ApiClient({
 'appkey':config.app_key,
 'appsecret':config.app_secret,
 'url':'http://gw.api.taobao.com/router/rest'
});*/
//后台API，可获取头像 

var config2 = {
    app_key: "24527543",
    app_secret: "a53cff85b5110d6cae3882372812ca7d",
    redirect_uri: "http://vrbuy.ews.m.jaeapp.com/oauth2"
}
var backClient = new ApiClient({
    'appkey': config2.app_key,
    'appsecret': config2.app_secret,
    'url': 'http://gw.api.taobao.com/router/rest'
});

var secretKey = {
    key: '751f620ea3c8f930',
    iv: '2624750004398718',
}


var mobilesocket = [];
var allRoom = {}


//发送数据到所有mobile socket用户
function sendToAllMobile(data, roomPeople) {
    if (roomPeople && !Object.keys(roomPeople).length) {
        return false;
    }
    for (var t in roomPeople) {
        try {
            if (roomPeople[t].ws) {
                roomPeople[t].ws.send(data);
            }
        } catch (e) {
            // console.log(e);
        }

    }
}
//发送数据到指定mobile socket用户
function sendToMobileByuserID(data, roomPeople,users) {
    if (roomPeople && !Object.keys(roomPeople).length) {
        return false;
    }
    for (var t in roomPeople) {
        try {
            for(var key in users){
                console.log(key,t);
                if (roomPeople[t].ws && roomPeople[t].userid == users[key]) {
                    roomPeople[t].ws.send(data);
                }
            }

    } catch (e) {
            // console.log(e);
        }

    }
}
function sendToBigScreen(data, room) {
    try {
        if (room) {
            room.send(data);
        }
    } catch (e) {
        // console.log(e);
    }
}
function getJoinRoomstr(curid, mixnick, headimgurl) {
    mixnick = mixnick + '';
    var nickname = mixnick.split('')[0];
    var joinroom = {
        cmd: 1,
        userid: curid,
        users: [{
            id: curid,
            headimgurl: headimgurl,
            "nickname": nickname + '****'
        }]
    }
    return JSON.stringify(joinroom);
}


function getEnterRoomstr(curid, mixnick, headimgurl) {
    mixnick = mixnick + '';
    var nickname = mixnick.split('')[0];
    var enterroom = {
        cmd: 2,
        info: {
            id: curid,
            headimgurl: headimgurl,
            "nickname": nickname + '**'
        }
    };
    return JSON.stringify(enterroom);
}

function getsyncstr(info) {
    var countdown = {
        cmd: 5,
        info: info
    }
    return JSON.stringify(countdown);
}

exports.register = function (server, option, next) {

    const sequelize = server.app.db;
    var dataBase = {
        //团购iteam表
        socketgame_iteam: sequelize.define('socketgame_iteam', {
            iteam_id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true
            }
        }, {
            freezeTableName: true,
            timestamps: true,
            underscoredAll: true
        }),
        //团购user表
        socketgame_user: sequelize.define('socketgame_user', {
            user_id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            wechat_id: {
                type: Sequelize.STRING
            },
            taobao_id: {
                type: Sequelize.STRING
            },
            wangwang_id: {
                type: Sequelize.STRING
            },
            avatar: {//头像
                type: Sequelize.STRING
            },
            realname: {
                type: Sequelize.STRING
            },
            telephone: {
                type: Sequelize.STRING
            },
            iteam_id: {
                type: Sequelize.INTEGER
            },
            service: {
                type: Sequelize.STRING
            }
        }, {
            freezeTableName: true,
            timestamps: true,
            underscoredAll: true
        })
    }

    var dataFn = require('../server/socketgame')(dataBase, sequelize)
    var curid = 0;
    const wss = new WebSocket.Server({server: server.listener});
    try {

        wss.on('connection', function connection(ws, req) {
            ws.on('message', function incoming(datastr) {
                var data = JSON.parse(datastr);

                if (data.cmd == 1 && data.info.type == 1) {
                    if (data.info.info) {
                        allRoom[data.info.roomName] = {}
                        allRoom[data.info.roomName].roomSocket = ws;
                        allRoom[data.info.roomName].people = {}
                        // allRoom[data.info.roomName].nicknameArr=[];
                    }
                } else if (data.cmd == 1 && data.info.type == 2) {
                    try{
                       console.log(allRoom[data.info.roomName].people)
                       var headimgurl = data.info.info.headimgurl;
                       var mixnick = data.info.info.nickname;
                      //  if( allRoom[data.info.roomName]&& allRoom[data.info.roomName].nicknameArr){
                      //     allRoom[data.info.roomName].nicknameArr.push(mixnick);
                      // }

                      var peopleMsg = {nickName: data.info.info.nickname, ws: ws};
                      if (allRoom[data.info.roomName] && allRoom[data.info.roomName].people && allRoom[data.info.roomName].roomSocket) {    
                        if (!allRoom[data.info.roomName].people[peopleMsg.nickName]) {
                            allRoom[data.info.roomName].people[peopleMsg.nickName] = peopleMsg;
                            curid = Object.keys(allRoom[data.info.roomName].people).length + 1;
                            allRoom[data.info.roomName].people[peopleMsg.nickName].userid=curid;
                        }else{
                            allRoom[data.info.roomName].people[peopleMsg.nickName].ws = ws;
                            curid =  allRoom[data.info.roomName].people[peopleMsg.nickName].userid;
                        }
                        ws.send(getJoinRoomstr(curid, mixnick, headimgurl));
                        sendToBigScreen(getEnterRoomstr(curid, mixnick, headimgurl), allRoom[data.info.roomName].roomSocket);
                        sendToAllMobile(getEnterRoomstr(curid, mixnick, headimgurl), allRoom[data.info.roomName].people);
                    }
                }
                catch(e){
                    console.log('wrong',e);
                }

            } else if (data.cmd == 5) {
                if (allRoom[data.info.roomName] && allRoom[data.info.roomName].people && allRoom[data.info.roomName].roomSocket) {
                    // console.log('000000000000000000',data.info,allRoom[data.info.roomName].people);
                    sendToBigScreen(getsyncstr(data.info.info), allRoom[data.info.roomName].roomSocket);
                    // sendToAllMobile(getsyncstr(data.info.info), allRoom[data.info.roomName].people);
                    // console.log(data.info.users);
                    sendToMobileByuserID(getsyncstr(data.info.info), allRoom[data.info.roomName].people,data.info.users);
                    // console.log(data.info.users);
                    // console.log(allRoom[data.info.roomName].people)
                  /*  if(data.info.users.length ==1 ){
                        var key =data.info.users[0]-2;
                        var nickname=allRoom[data.info.roomName].nicknameArr[key];
                     
                        var roomPeople = {};
                        roomPeople.nickname = {'nickName':nickname,'ws':allRoom[data.info.roomName].people[nickname].ws};
                        console.log(roomPeople);
                           sendToAllMobile(getsyncstr(data.info.info), roomPeople);
                        // console.log(key,allRoom[data.info.roomName].nicknameArr[key],allRoom[data.info.roomName].people.nickname);
                    }else{
                        sendToAllMobile(getsyncstr(data.info.info), allRoom[data.info.roomName].people);
                    }*/


                }
            }
            else if (data.cmd == 7) {
                if (allRoom[data.info.roomName] && allRoom[data.info.roomName].people) {
                    allRoom[data.info.roomName].people = {}
                }
            }
        });
});
} catch (e) {
    console.log(e);
}


    /*
     * /groupon/iteam/add
     * @interface 后台开团
     * @method POST
     * @param null
     * @return json {errCode:0,msg:'ok',data:{id:**}}
     */

     server.route({
        method: ['GET', 'POST'],
        path: '/socketgame/getAvatar',
        handler: function (request, reply) {
            var options = request.payload || request.url.query;
            console.log(222222222222222222222222222222222222, options);
            dataFn.user.getAvatar(options.mixnick, backClient).then(imgurl => {
                return reply(imgurl);
            });
        }
    });
     return next();
 }

 exports.register.attributes = {
    name: 'route-socket'
}